package com.xuecheng.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.config.MultipartSupportConfig;
import com.xuecheng.execption.XueChengPlusException;
import com.xuecheng.feignclient.MediaServiceClient;
import com.xuecheng.mapper.CoursePublishMapper;
import com.xuecheng.model.dto.CourseBaseInfoDto;
import com.xuecheng.model.dto.CoursePreviewDto;
import com.xuecheng.model.dto.TeachplanDto;
import com.xuecheng.model.po.CourseBase;
import com.xuecheng.model.po.CoursePublish;
import com.xuecheng.service.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author 小班哥
 * @since 2023-04-15
 */
@Service
@Slf4j
public class CoursePublishServiceImpl extends ServiceImpl<CoursePublishMapper, CoursePublish> implements CoursePublishService {

    @Autowired
    private CourseBaseInfoService courseBaseInfoService;

    @Autowired
    private TeachplanService teachplanService;


    @Autowired
    private CoursePublishService coursePublishService;

    @Resource
    private MediaServiceClient mediaServiceClient;


    /**
     *
     * @param courseID 课程ID
     * @return
     */
    @Override
    public CoursePreviewDto GetCoursePreviewInfo(long courseID) {
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        //查询课程的基本信息，营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseID);
        //查询课程的计划信息
        List<TeachplanDto> teachplayTree = teachplanService.findTeachplayTree(courseID);
        coursePreviewDto.setCourseBase(courseBaseInfo);
        coursePreviewDto.setTeachplans(teachplayTree);
        return coursePreviewDto;
    }


    /**
     *
     * @param courseId  课程id
     * @return
     */
    @Override
    public File generateCourseHtml(Long courseId) {
        File tempFile;
        try {
            //创建FreeMarker的配置对象，并指定版本，getVersion()拿到当前版本
            Configuration configuration = new Configuration(Configuration.getVersion());
            //拿到classpath路径
            String path = this.getClass().getResource("/templates").getPath();
            //指定模板目录
            configuration.setDirectoryForTemplateLoading(new File(path ));
            //指定编码
            configuration.setDefaultEncoding("UTF-8");
            //得到模板
            Template template = configuration.getTemplate("course_template.ftl");
            //拿到数据
            CoursePreviewDto coursePreviewDto = coursePublishService.GetCoursePreviewInfo(courseId);
            //将数据封装成Map
            HashMap<String, CoursePreviewDto> previewDtoHashMap = new HashMap<>();
            previewDtoHashMap.put("model" , coursePreviewDto);
            //生成HTML页面
            String HtmlData = FreeMarkerTemplateUtils.processTemplateIntoString(template, previewDtoHashMap);
            //将生成的数据写入文件中
            byte[] bytes = HtmlData.getBytes(StandardCharsets.UTF_8);
            //生成一个临时文件
            tempFile = File.createTempFile(courseId.toString(), ".html");
            String absolutePath = tempFile.getAbsolutePath();
            Files.write(Paths.get(absolutePath), bytes);
        } catch (Exception e) {
            log.debug("页面静态化失败，课程ID:{},异常信息{}",courseId , e.getMessage());
            throw new XueChengPlusException("生成课程预览页面失败!");
        }
        return tempFile;
    }


    /**
     *
     * @param courseId 课程id
     * @param file  静态化文件
     */
    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        //将file转成MultipartFile
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        //拿到文件的后缀
        String substring = courseId + file.getName().substring(file.getName().lastIndexOf('.'));
        //上传文件
        String s = mediaServiceClient.FileUpload(multipartFile, "/course/" + substring);
        //删除临时文件
        file.delete();
        if (s==null){
            throw new XueChengPlusException("上传静态化页面异常!");
        }
    }

    /**
     * 查询课程发布信息
     * @param courseID 课程ID
     * @return
     */
    @Override
    public CoursePublish getCoursePublish(long courseID) {
        return coursePublishService.getById(courseID);
    }

}
